#include <gtk/gtk.h>
#include <stdlib.h>
#include <time.h>
#include "gui.h"
#include "board.h"
#include "threads.h"

#ifdef WIN32
#include <windows.h>
#endif

/* Pomocnicza struktura wskaźników na elementy GUI */
volatile struct Gui gui;

/* Bieżąca plansza do gry, dla bezpieczeństwa */
/* wskaźnik ustawiony na volatile */
volatile Board* plansza;

#define UI_FILE "omringa.ui"
#define UI_EDITOR_FILE "editor.ui"

/* Signal handlers */
/* Note: These may not be declared static because signal autoconnection
 * only works with non-static methods
 */

/* Called when the window is closed */
G_MODULE_EXPORT void
destroy (GtkWidget *widget, gpointer data)
{
	
	/* zakończ wątki */
	thread_interrupt();

	/* zwolnij planszę */
	if(plansza != NULL)
		free((Board*)plansza);
	
	gtk_main_quit ();
	
}

static GtkWidget*
create_window (void)
{
	GtkWidget *window;
	GtkBuilder *builder;
	GError* error = NULL;

	/* Load UI from files */

	builder = gtk_builder_new ();
	
	if (!gtk_builder_add_from_file (builder, UI_FILE, &error))
	{
		g_warning ("Couldn't load builder file: %s", error->message);
		g_error_free (error);
	}

	if (!gtk_builder_add_from_file (builder, UI_EDITOR_FILE, &error))
	{
		g_warning ("Couldn't load builder file: %s", error->message);
		g_error_free (error);
	}
		
	gui_init((struct Gui*)&gui, builder);

	/* Auto-connect signal handlers */
	gtk_builder_connect_signals (builder, NULL);

	/* Get the window object from the ui file */
	window = GTK_WIDGET (gtk_builder_get_object (builder, "window"));
	
	return window;
}

#ifdef WIN32

int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil)

#else

int
main (int argc, char *argv[])

#endif

{

	GtkWidget* window;

	g_thread_init(NULL);
    gdk_threads_init();

	gdk_threads_enter();
	
	gtk_init (NULL, NULL);
	
	srand(time(0));
	plansza = NULL;
	
	window = create_window ();
	gtk_widget_show (GTK_WIDGET(window));
	
	gtk_main ();
	
	gdk_threads_leave();

	return 0;
}
